//Map
var map;
//Lat,Lng of init position
var init_lat = 10.412183158667512;
var init_lng = 108.08349609375;
//Zoom
var zoomRate = 16;
//Geocode : convert Address string to Location on map (Lat,Lng)
//var geocoder;
//Address string will be input by user
var nt_address = "";
//Maker
var nt_marker;
var nt_markercount = 0;
//Info window
var nt_infowindow;

/*Load function*/
function initialize(address, lat, lng) {
	geocoder = new google.maps.Geocoder();
	if (address != null) {
		init_lat = lat;
		init_lng = lng;
		nt_address = address;
	}
	var latlng = new google.maps.LatLng(init_lat, init_lng);
	var mapOptions = {
		zoom: zoomRate,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
    
    //Setup geocoder for new order marker
    google.maps.event.addListener(map, 'click', function(event) {
    	newMarkerOrder(event.latLng);
    });
    
    //Set current pos center using HTML5
	placeMarkerCurrentPos();
  }

/*Convert address to location*/
function codeAddress() {
	var address = document.getElementById('dia_chi').value;
	geocoder.geocode( { 'address': address}, function(results, status) {
	    if (status == google.maps.GeocoderStatus.OK) {
	    	map.setCenter(results[0].geometry.location);
	    	var marker = new google.maps.Marker({
	    		map: map,
	    		position: results[0].geometry.location
	    	});
	    } else {
	    	alert('Không thể xác định  vị trí này theo địa chỉ . '+address);
	    }
	});
}

//Execute when input text change
function placeChange() {
	var address = document.getElementById("dia_chi").value;
	var selID = document.getElementById("thanh_pho");
	var city = selID.options[selID.selectedIndex].text;
	selID = document.getElementById("quan_huyen");
	var district = selID.options[selID.selectedIndex].text;
	address = address + ", " + city + ", " + district;
	
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			var pos = results[0].geometry.location;
			
			//Address after formated
			var formatted_address =  results[0].formatted_address;
			if (nt_markercount == 0) {
				nt_markercount++;
				nt_marker = new google.maps.Marker({
					position : pos,
					map : map,
					icon : "/public/img/map_pin.png",
					draggable : true,
					title : "Địa chỉ nhà trọ",
					zIndex : 1
				});
				var infowindowMarkerNewOrder = {
					content : setContentNewOrderInfoWindow(formatted_address, pos.lat(), pos.lng()),
					maxWidth: 200
				};
				infowindowNew = new google.maps.InfoWindow(infowindowMarkerNewOrder);
				infowindowNew.setContent(nt_address);
				nt_marker['infowindow'] = infowindowNew;
				infowindowNew.setContent(setContentNewOrderInfoWindow(formatted_address, pos.lat(), pos.lng()));
				if (infowindowNew) {
					infowindowNew.close();
				}
				infowindowNew.open(map, nt_marker);

				google.maps.event.addListener(nt_marker,'dragend', function() {
					map.setCenter(pos);
					geocoder.geocode({latLng : nt_marker.getPosition()},
					function(results1, status1) {
						if (status1 == google.maps.GeocoderStatus.OK) {
							nt_address = results1[0].formatted_address;
							infowindowNew.setContent(setContentNewOrderInfoWindow(
								nt_address,
								nt_marker.getPosition().lat(),
								nt_marker.getPosition().lng()
							));
							if (infowindowNew) {
								infowindowNew.close();
							}
							infowindowNew.open(map,nt_marker);
						} else {
							nt_marker.setPosition(pos);
							nt_address = 'Không thể xác định địa chỉ tại vị trí này.';
							alert(nt_address);
						}
					});
				});
			} else {
				nt_marker.setPosition(pos);
				infowindowNew.setContent(setContentNewOrderInfoWindow(
					formatted_address,
					pos.lat(),
					pos.lng()
				));
				if (infowindowNew) {
					infowindowNew.close();
				}
				infowindowNew.open(map, nt_marker);
			}
  
		}
	});						
}

// Place new order marker
function newMarkerOrder(pos) {
	map.setCenter(pos);
	geocoder.geocode({latLng : pos}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			nt_address = results[0].formatted_address;
			if (nt_markercount == 0) {
				nt_markercount++;
				nt_marker = new google.maps.Marker({
					position : pos,
					map : map,
					icon : "/public/img/map_pin.png",
					draggable : true,
					title : "Giữ chuột và di chuyển đến vị trí nhà trọ",
					zIndex : 1
				});
				var infowindowMarkerNewOrder = {
					content : setContentNewOrderInfoWindow(nt_address, pos.lat(), pos.lng()),
					maxWidth: 200
				};
				infowindowNew = new google.maps.InfoWindow(infowindowMarkerNewOrder);
				infowindowNew.setContent(nt_address);
				nt_marker['infowindow'] = infowindowNew;
				infowindowNew.setContent(setContentNewOrderInfoWindow(
					nt_address, pos.lat(),pos.lng()
				));
				if (infowindowNew) {
					infowindowNew.close();
				}
				infowindowNew.open(map, nt_marker);
				google.maps.event.addListener(nt_marker,'dragend', function() {
					map.setCenter(pos);
					geocoder.geocode({latLng : nt_marker.getPosition()},
					function(results1, status1) {
						if (status1 == google.maps.GeocoderStatus.OK) {
							nt_address = results1[0].formatted_address;
							infowindowNew.setContent(setContentNewOrderInfoWindow(
								nt_address,
								nt_marker.getPosition().lat(),
								nt_marker.getPosition().lng()));
								if (infowindowNew) {
									infowindowNew.close();
								}
								infowindowNew.open(map,nt_marker);
						} else {
							nt_marker.setPosition(pos);
							nt_address = 'Không thể xác định địa chỉ tại vị trí này.';
							alert(nt_address);
						}
					});
				});
			} else {
				nt_marker.setPosition(pos);
				infowindowNew.setContent(setContentNewOrderInfoWindow(
					nt_address,
					pos.lat(),
					pos.lng()
				));
				if (infowindowNew) {
					infowindowNew.close();
				}
				infowindowNew.open(map, nt_marker);
			}
		} else {
			nt_address = 'Không thể xác định địa chỉ tại vị trí này.';
		}
	});
	//customize map center
	map.panBy(0,-80);
	//add click listener for marker
	google.maps.event.addListener(nt_marker, "click", function() {
		infowindowNew.open(map, nt_marker);
	});
	
}

//Place marker at current position
function placeMarkerCurrentPos() {
	navigator.geolocation.getCurrentPosition(GetLocation);
	function GetLocation(location) {
		newMarkerOrder(new google.maps.LatLng(
			location.coords.latitude, location.coords.longitude
		));
	}
}

//Create html string for new order marker
function setContentNewOrderInfoWindow(address, lat, lng) {
	var titleStyle = "style='color:red; font-size:14px; '";
	var latLngStyle = "style='color:green; font-size:12px; '";
	var htmlString = "<b " + titleStyle + ">" + address + "</b></br>";
	if (document.getElementById("latitude")) {
		document.getElementById("latitude").value = lat;
		document.getElementById("longitude").value = lng;
	}
	return htmlString;
}

//Create map display a location- view detail
function displayLocation(_address,_lat,_lng)
{
	var _geocoder = new google.maps.Geocoder();
	var _posinit = new google.maps.LatLng(init_lat, init_lng);
	var _pos = _posinit;
	var _mapOptions = {
		zoom: zoomRate,
		center: _pos,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    };
	
    var _map = new google.maps.Map(document.getElementById("map_canvas"), _mapOptions);
    //Co toa do
    if(_lat&&_lng&&_lat.length&&_lng.length){
    	_pos =new google.maps.LatLng(_lat,_lng);
    	if(!_address||!_address.length){
			_geocoder.geocode({latLng : _pos },
					function(_results1, _status1) {
						if (_status1== google.maps.GeocoderStatus.OK) {
							_address = _results1[0].formatted_address;
							createMarkerAndInfowindow(_pos,_address,_map);
							return;
							
						} else {
							_address = 'Người đăng tin chưa cung cấp đầy đủ thông tin về địa chỉ.';
							createMarkerAndInfowindow(_posinit,_address,_map);
							return;
						}
		    });
    	}else{
			createMarkerAndInfowindow(_pos,_address,_map);
			return;
    	}
    	
    }else{//Neu khong co toa do-> get toa do tu dia chi
    	if(_address&&_address.length){
    		_geocoder.geocode({'address' : _address}, function(_results, _status) {
				if (_status == google.maps.GeocoderStatus.OK) {
					_pos=_results[0].geometry.location;
					createMarkerAndInfowindow(_pos,_address,_map);
				}
    		});
    }
    	else{
    		_address="Người đăng tin chưa cung cấp đầy đủ thông tin về địa chỉ.";
    		createMarkerAndInfowindow(_pos,_address,_map);
    	}
    }
   
   
}
function createMarkerAndInfowindow(pos,addr,map){
	//create marker
	var nt_marker = new google.maps.Marker({
		position : pos,
		map :map,
		icon : "/public/img/map_pin.png",
		draggable : false,
		title : "Vị trí nhà trọ",
		zIndex : 1
	});
	//create infowindow
	var titleStyle = "style='color:red; font-size:14px; '";
	var htmlString = "<b id='inforstr'" + titleStyle + ">" + addr + "</b></br>";
	var infowindowOption = {
			content : htmlString,
			maxWidth: 200
	};
	_infowindowNew = new google.maps.InfoWindow(infowindowOption);
	nt_marker['infowindow'] = _infowindowNew;
	if (_infowindowNew) {
		_infowindowNew.close();
	}
	_infowindowNew.open(map, nt_marker);
	map.panBy(0,-80);
	google.maps.event.addListener(nt_marker, 'click', function() {
		_infowindowNew.open(map, nt_marker);	
	});
}